package com.gxitsky.plugin.servlet3;

import javax.servlet.AsyncContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author gxing
 * @desc TODO
 * @date 2022/1/6
 */
@WebServlet(urlPatterns = "AsyncRunningServlet", asyncSupported = true)
public class AsyncRunningServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        long startTime = System.currentTimeMillis();
        System.out.println("AsyncRunningServlet Start | Name=" + Thread.currentThread().getName());
        request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);

        String time = request.getParameter("time");
        int processTime = Integer.parseInt(time);

        if (processTime > 5000) {
            processTime = 5000;
        }
        AsyncContext asyncContext = request.getAsyncContext();
        asyncContext.addListener(new MyAsyncListener());
        asyncContext.setTimeout(4000);
        ThreadPoolExecutor executor = (ThreadPoolExecutor) request.getServletContext().getAttribute("executor");
        executor.execute(new AsyncRequestProcess(asyncContext, processTime));
        long endTime = System.currentTimeMillis();
        System.out.println("AsyncRunningServlet End | Name=" + Thread.currentThread().getName());
        System.out.println("Time Cost:" + (endTime - startTime));
    }
}
